package com.smartlock.service;

import java.util.concurrent.*;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartlock.param.RemoteUnLockParam;
import com.smartlock.util.HttpClientUtil;

public class BackgroundService {

    private static final Logger    logger          = LoggerFactory.getLogger(BackgroundService.class);

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void pushToBackground(String url, Object paramObj) {
        executorService.execute(() -> {
            String pushReturnMsg = HttpClientUtil.postWithJson(url, JSON.toJSONString(paramObj));
            logger.debug("后台推送Url:" + url + ",推送结果：" + pushReturnMsg);
        });
    }

    public static JSONObject reqBackground(String url, Object paramObj) {

        Future future = executorService.submit(() -> {
            String returnMsg = HttpClientUtil.postWithJson(url, JSON.toJSONString(paramObj));
            logger.debug("后台请求Url:" + url + ",请求结果：" + returnMsg);
            return returnMsg;
        });
        String returnMsg = null;
        try {
            returnMsg = (String) future.get(1, TimeUnit.SECONDS);
            if (StringUtils.isBlank(returnMsg)) {
                return null;
            }
        } catch (InterruptedException e) {
            logger.info("请求后台数据线程中断！请求参数：" + JSON.toJSONString(paramObj));
        } catch (ExecutionException e) {
            logger.info("请求后台数据线程中断！请求参数：" + JSON.toJSONString(paramObj));
        } catch (TimeoutException e) {
            logger.info("请求后台数据线程超时！请求参数：" + JSON.toJSONString(paramObj));
        }
        return JSONObject.parseObject(returnMsg);
    }

    public static void main(String[] args) {
        String url = "http://116.62.142.20:89/lock/remoteUnLock";
        RemoteUnLockParam param = new RemoteUnLockParam();
        param.setCommand("01");
        param.setLockMac("8F,94,F8,5F,49,2D,");
        param.setLockPwd("01,02,03,04,05,06");
        param.setUnLockNo("00,0A");
        String result = HttpClientUtil.postWithJson(url, JSON.toJSONString(param));
        System.out.println(result);
    }

}
